<template>
  <view class="pick-bgi">
    <view class="page1" v-if="pageTabbarAc == 0">
      <view class="main-tabbar">
        <view :class="['tabbar-item-1', tabbarAc == item.id ? 'ac' : '']" v-for="(item, index) in tabbarList" :key="item.id" @click="changeTabbarAc({ item, index })">
          <view class="text">{{ item.text }}</view>
        </view>
      </view>
      <view class="main-content">
        <view class="chun" v-if="tabbarAc == 1 && 0">
          <view class="colorList">
            <view class="color-item" :style="{ background: item.tabbarColor }" v-for="(item, index) in colorList" :key="item.id" @click="selectColorBgi({ item, index })"></view>
          </view>
          <!-- <view class="confirmBtn">确认</view> -->
        </view>
        <view class="main-tabbar" v-if="tabbarAc == 1">
          <view :class="['tabbar-item', tabbarAc2 == item.id ? 'ac' : '']" v-for="(item, index) in tabbarList2" :key="item.id" @click="changeTabbarAc2({ item, index })">
            <view class="text">{{ item.classifyName }}</view>
          </view>
        </view>
        <view class="contentList" v-if="tabbarAc == 1" @scroll="contentListScroll" ref="bgiContentList">
          <view class="contentItem" v-for="(item, index) in yushe" @click="pickContentItem({ item, index })" :key="item.id">
            <image class="pic" :src="pageItem.ac == 2 ? item.matterUrl : ''" mode="heightFix"></image>
            <view class="bottom">
              <view class="name">{{ item.matterName }}</view>
            </view>
          </view>
        </view>
        <view class="contentList" v-if="tabbarAc == 2" @scroll="contentListScroll" ref="bgiContentList">
          <view class="contentItem first" :style="{ '--height-val': 'calc(30vh - 9vw)' }" @click="addContentItem()">
            <image class="pic add" :src="imgPath + 'createAvatar/changjing-add.svg'" mode="heightFix"></image>
            <view class="bottom">
              <view class="name">{{ "本地上传" }}</view>
            </view>
          </view>
          <view class="contentItem" v-for="(item, index) in geren" @click="pickContentItem({ item, index })" :key="item.id" :style="{ '--height-val': 'calc(30vh - 9vw)' }">
            <image class="pic" :src="pageItem.ac == 2 ? item.matterUrl : ''" mode="heightFix"></image>
            <view class="bottom">
              <view class="name">{{ item.matterName }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="page2" v-if="pageTabbarAc == 1">
      <view class="main-edit">
        <view class="btns">
          <view class="btn-item" @tap="del()">
            <image class="icon" :src="imgPath + 'createAvatar/del.svg'" mode=""></image>
            <view class="text">删除</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>
<script>
import * as api from "@/api/createVideo.js";
import axios from "axios";
let timer = null;
import { tools } from "../../../../utils/util";
export default {
  props: {
    show: {
      type: Boolean,
      default: false
    },
    promiseRes: {
      type: Object | Function,
      default() {
        return null;
      }
    },
    currInd: {
      type: Number,
      default: -1
    },
    scene2: {
      type: Array,
      default() {
        return [];
      }
    },
    pageItem: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      imgPath: tools.imgPath,
      pageTabbarAc: 0,
      pageTabbarList: [],
      colorList: [],
      tabbarAc: 1,
      tabbarList: [],
      tabbarAc2: null,
      tabbarList2: [],
      yushe: [],
      yusheCurrent: 1,
      yusheSize: 8,
      yusheTotal: null,
      geren: [],
      gerenCurrent: 1,
      gerenSize: 999,
      gerenTotal: null,
      uploadFileSize: 200
    };
  },
  async created() {
    this.initPageTabbarList();
    this.initColorList();
    this.initTabbarList();
    let next = await this.initGetData();
    if (this.promiseRes) {
      this.promiseRes(true);
    }
  },
  methods: {
    // 本地上传
    addContentItem() {
      const that = this;
      uni.chooseImage({
        success: (chooseImageRes) => {
          const tempFilePaths = chooseImageRes.tempFilePaths;
          let file = chooseImageRes.tempFiles[0];
          let name = file.name;
          if (!/^[\u4e00-\u9fa5a-zA-Z0-9\.\-]+$/.test(name)) {
            return tools.easyToast("文件名不能包含符号，只能是文字或数字");
          }
          if (file.size / 1024 / 1024 > this.uploadFileSize) {
            return tools.easyToast(`文件大小超过${this.uploadFileSize}M!`);
          }
          var img = new Image();
          img.src = chooseImageRes.tempFilePaths[0];
          img.onload = async function () {
            let { naturalWidth, naturalHeight } = img;
            let ossData = await api.postOSS({
              reqType: "mat_image_back",
              matName: name,
              payLoad: {
                height: naturalHeight,
                wide: naturalWidth
              }
            });
            let res = await that.getOSSApi_new(ossData, file, name);
            if (!res) return;
            // console.log(res.src);
            that.geren = [];
            that.getDataApi2();
          };
        }
      });
    },
    //上传文件api
    async getOSSApi_new(ossData, file, name) {
      const that = this;
      let res = ossData;

      function getUUID() {
        let keyStr = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
        keyStr = "xxxxxxxx-6xxx";
        return keyStr.replace(/[xy]/g, (c) => {
          return (c === "x" ? (Math.random() * 16) | 0 : "r&0x3" | "0x8").toString(16);
        });
      }
      const formData = new FormData();
      let url_name = "https://alleymall.oss-cn-guangzhou.aliyuncs.com";
      let key = res.data.dir + "/" + getUUID() + name;
      formData.append("policy", res.data.policy);
      formData.append("signature", res.data.signature);
      formData.append("ossaccessKeyId", res.data.accessid);
      formData.append("key", key);
      formData.append("dir", res.data.dir);
      formData.append("host", res.data.host);
      formData.append("expire", res.data.expire);
      formData.append("callback", res.data.callback);
      // formData.append('type', res.data.callback)
      formData.append("file", file);

      return axios
        .post(url_name, formData, {
          headers: {
            "Content-Type": "multipart/form-data"
          }
        })
        .then((response) => {
          let src = url_name + "/" + key;
          // console.log(src);
          // that.audioPlayerSrc = src;
          // console.log(response);
          return {
            ...response,
            src
          };
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 滚动事件(做懒加载)
    contentListScroll(event) {
      if (this.tabbarAc2 == "color") return;
      const that = this;
      if (timer) clearTimeout(timer);
      timer = setTimeout(() => {
        let target = this.$refs.bgiContentList.$el;
        if (target.scrollWidth - 5 < target.scrollLeft + target.offsetWidth) {
          if (that.tabbarAc == 1) {
            if (this.yusheTotal === this.yushe.length) return;
            this.yusheCurrent++;
            this.getDataApi();
          } else {
            if (this.gerenTotal === this.geren.length) return;
            this.gerenCurrent++;
            this.getDataApi2();
          }
        }
        clearTimeout(timer);
        timer = null;
      }, 300);
    },
    // 获取公共数据分类api
    async getSysmatTwoType() {
      const type = "bgi";
      let res = await api.getSysmatTwoType(type);
      if (!res) return;
      this.tabbarList2 = [
        {
          id: null,
          classifyName: "全部"
        },
        {
          id: "color",
          classifyName: "纯色"
        },
        ...res.data
      ];
      this.tabbarAc2 = this.tabbarList2[0].id;
      return true;
    },
    // 获取公共数据api
    async getDataApi(_id) {
      _id = ["Null", "Number", "String"].includes(tools.myTypeOf(_id)) ? _id : this.tabbarAc2;
      let res = null;
      if (!_id) {
        //获取全部数据
        let data = {
          type: "bgi",
          size: this.yusheSize,
          current: this.yusheCurrent,
          id: 2 //横屏1，竖屏2
        };
        res = await api.getVideoSysmatAll(data);
      } else if (_id == "color") {
        //获取纯色

        res = this.initColorList();
      } else {
        //获取分类数据
        let data = {
          oneid: _id,
          size: this.yusheSize,
          current: this.yusheCurrent,
          twoid: 2 //横屏1，竖屏2
        };
        res = await api.getVideoSysmat(data);
      }
      if (!res?.data?.records) {
        this.yushe = [];
        this.yusheTotal = null;
        return;
      }
      this.yusheTotal = res.data.total;
      let yushe = res.data.records.map((e) => ({
        ...e,
        picSrc: e.matterUrl?.replace("https://alleymall.oss-cn-guangzhou.aliyuncs.com/", `${location.origin}/assets/`) || null
      }));
      this.yushe = [...this.yushe, ...yushe];
      return true;
    },
    // 获取私有数据api
    async getDataApi2() {
      let res = await api.getUserSource("image_back");
      if (!res) return;
      this.geren = res.data.map((e) => ({
        ...e,
        picSrc: e.matterUrl?.replace("https://alleymall.oss-cn-guangzhou.aliyuncs.com/", `${location.origin}/assets/`) || null
      }));
      return true;
    },
    // 获取后端数据
    async initGetData() {
      let getData = new Promise(async (next) => {
        let flag = await this.getSysmatTwoType();
        if (!flag) return;
        let flag2 = await this.getDataApi();
        if (!flag2) return;
        next(true);
      });
      await Promise.all([getData]);
      return true;
    },
    // 初始化contentList
    initContentList() {
      this.contentList = matData.map((e) => ({
        ...e,
        picSrc: e.matterUrl
      }));
    },
    // 选择颜色背景
    selectColorBgi({ item, index }) {
      item.picSrc = item.colorShuUrl;
      this.$emit("pickBgi", {
        item,
        index
      });
    },
    // 初始化ColorList
    initColorList() {
      this.colorList = [
        {
          imgBgI: "",
          colorShuUrl: "https://alleymall.oss-cn-guangzhou.aliyuncs.com/2023-11-20/f6690832-6317fengmian.png",
          colorHengUrl: "https://alleymall.oss-cn-guangzhou.aliyuncs.com/2023-11-20/7d80c46a-6a9dfengmian.png",
          tabbarColor: "#6fcf97",
          name: "预设背景"
        },
        {
          imgBgI: "",
          colorShuUrl: "https://alleymall.oss-cn-guangzhou.aliyuncs.com/2023-11-20/b438ab8e-67d4fengmian.png",
          colorHengUrl: "https://alleymall.oss-cn-guangzhou.aliyuncs.com/2023-11-20/b740388e-60b0fengmian.png",
          tabbarColor: "#e74032",
          name: "预设背景"
        },
        {
          imgBgI: "",
          colorShuUrl: "https://alleymall.oss-cn-guangzhou.aliyuncs.com/2023-11-20/2e464b6a-6ca1fengmian.png",
          colorHengUrl: "https://alleymall.oss-cn-guangzhou.aliyuncs.com/2023-11-20/1de5ab36-6be3fengmian.png",
          tabbarColor: "#fabe13",
          name: "预设背景"
        },
        {
          imgBgI: "",
          colorShuUrl: "https://alleymall.oss-cn-guangzhou.aliyuncs.com/2023-11-20/75efa69d-6003fengmian.png",
          colorHengUrl: "https://alleymall.oss-cn-guangzhou.aliyuncs.com/2023-11-20/fae4131f-6682fengmian.png",
          tabbarColor: "#2260ec",
          name: "预设背景"
        },
        {
          imgBgI: "",
          colorShuUrl: "https://alleymall.oss-cn-guangzhou.aliyuncs.com/2023-11-20/1c3fc492-61bbfengmian.png",
          colorHengUrl: "https://alleymall.oss-cn-guangzhou.aliyuncs.com/2023-11-20/c516e7ba-6c1cfengmian.png",
          tabbarColor: "#FFFFFF",
          name: "预设背景"
        },
        {
          imgBgI: "",
          colorShuUrl: "https://alleymall.oss-cn-guangzhou.aliyuncs.com/2023-11-20/2fa764fa-6849fengmian.png",
          colorHengUrl: "https://alleymall.oss-cn-guangzhou.aliyuncs.com/2023-11-20/9252e36d-626cfengmian.png",
          tabbarColor: "#000000",
          name: "预设背景"
        },
        {
          imgBgI: "",
          colorShuUrl: "https://alleymall.oss-cn-guangzhou.aliyuncs.com/2023-11-20/3a804a94-6debfengmian.png",
          colorHengUrl: "https://alleymall.oss-cn-guangzhou.aliyuncs.com/2023-11-20/769d4101-61adfengmian.png",
          tabbarColor: "#fc5531",
          name: "预设背景"
        }
      ].map((e, i, s) => {
        return {
          ...e,
          colorShuUrl: e.colorShuUrl?.replace("https://alleymall.oss-cn-guangzhou.aliyuncs.com/", `${location.origin}/assets/`),
          colorHengUrl: e.colorHengUrl?.replace("https://alleymall.oss-cn-guangzhou.aliyuncs.com/", `${location.origin}/assets/`),
          matterUrl: s[i]["colorShuUrl"]
        };
      });
      return {
        data: {
          records: this.colorList
        }
      };
    },
    // 初始化tabbarList
    initTabbarList() {
      this.tabbarList = [
        {
          text: "预设",
          id: 1
        },
        {
          text: "本地",
          id: 2
        }
      ];
    },
    //初始化pageTabbarList
    initPageTabbarList() {
      this.pageTabbarList = [
        {
          text: "选择背景图",
          id: 0
        },
        {
          text: "编辑背景图",
          id: 1
        }
      ];
      if (this.pageItem) {
        // console.log('初始化pageTabbarList',this.pageItem);
        this.pageTabbarAc = this.pageItem.pageAc;
      }
    },
    //切换页面类型
    changePageTabbarAc({ item, index }) {
      // if (this.pageTabbarAc == item.id) return;
      this.pageTabbarAc = item.id;
      if (this.pageTabbarAc == 0) {
        this.$emit("changeMyDH", 35);
      } else {
        this.$emit("changeMyDH", 16);
      }
    },
    // 切换类型
    changeTabbarAc({ item, index }) {
      this.tabbarAc = item.id;
      if (this.tabbarAc == 2) {
        //获取私有数据
        this.getDataApi2();
      }
    },
    //切换数据子类型
    changeTabbarAc2({ item, index }) {
      this.tabbarAc2 = item.id;
      this.yushe = [];
      this.yusheCurrent = 1;
      this.yusheTotal = null;
      this.getDataApi();
    },
    // 选择item
    pickContentItem({ item, index }) {
      this.$emit("pickBgi", {
        item,
        index
      });
    },
    // 删除
    del() {
      this.$emit("removeEl", this.currInd);
    },
    // 修改层级
    changeZIndex(num) {
      if (this.currInd == null || this.currInd < 0) {
        return tools.easyToast("请先选择背景图!");
        // if (index == -1) {
        // 	tools.easyToast('请先选择数字人!');
        // } else {
        // 	this.$emit('changeZIndex', this.currInd, num);
        // };
      } else {
        this.$emit("changeZIndex", this.currInd, num);
      }
    }
  },
  watch: {
    ["pageItem.ac"](val) {
      if (val != 2) return;
      this.changePageTabbarAc({
        item: {
          id: this.pageItem.pageAc
        }
      });
    }
  }
};
</script>

<style lang="scss">
.pick-bgi {
  padding: 5vw;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 100%;

  .page1 {
    display: flex;
    flex-direction: column;
    overflow: hidden;
    height: 100%;
  }

  .main-tabbar {
    display: -webkit-box;
    overflow: auto;

    .tabbar-item-1 {
      padding: 2vw;
      font-size: 32rpx;
      font-weight: 400;
      color: rgba(255, 255, 255, 1);
      display: flex;
      justify-content: center;
      align-items: center;

      &.ac {
        .text {
          color: rgba(0, 153, 127, 1);
          border-bottom: 2px solid rgba(243, 173, 51, 1);
        }
      }

      .text {
        padding-bottom: 2vw;
      }
    }

    .tabbar-item {
      padding: 0.5vw 1vw;
      color: rgba(255, 255, 255, 0.36);
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 100vw;
      background: rgba(255, 255, 255, 0.125);
      margin: 0vw 5vw 2vw 0vw;
      min-width: 10vw;

      &.ac {
        border: 2px solid rgba(0, 153, 127, 1);

        .text {
          color: rgba(0, 153, 127, 1);
          font-weight: 700;
        }
      }

      .text {
        font-size: 24rpx;
        font-weight: 400;
      }
    }
  }

  .main-content {
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .contentList {
      display: -webkit-box;
      overflow: auto;
      height: max-content;
      max-height: 100%;

      .contentItem {
        --height-val: calc(30vh - 22vw);
        width: max-content;
        height: var(--height-val);
        overflow: hidden;
        margin-right: 3vw;
        margin-bottom: 1.2vw;
        border-radius: 2vw;
        background: rgba(28, 43, 46, 1);
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;
        &.first {
          width: 30vw;
        }
        .pic {
          width: 100%;
          height: 100%;

          &.add {
            width: 30%;
            height: 30%;
          }
        }

        .tag {
          position: absolute;
          top: 0vw;
          left: 0vw;
          border-radius: 3vw 0vw 3vw 0vw;
          background: linear-gradient(270deg, rgba(0, 222, 185, 1) 0%, rgba(122, 255, 233, 1) 100%);
          font-size: 20rpx;
          font-weight: 400;
          color: rgba(22, 24, 30, 1);
          display: flex;
          justify-content: center;
          align-items: center;
          padding: 1vw 1.5vw;
        }

        .bottom {
          position: absolute;
          bottom: 0vw;
          width: 100%;
          height: 6vw;
          display: flex;
          justify-content: center;
          align-items: center;
          background: rgba(22, 24, 30, 0.7);
          font-size: 20rpx;
          font-weight: 400;
          color: rgba(204, 204, 204, 1);
        }
      }
    }

    .chun {
      display: flex;
      flex-direction: column;
      width: 100%;

      .colorList {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .color-item {
          height: 20vw;
          width: calc(77vw / 7);
          border-radius: 2vw;
        }
      }

      .confirmBtn {
        margin: 5vw 2vw;
        border-radius: 100vw;
        background: linear-gradient(270deg, rgba(0, 222, 185, 1) 0%, rgba(122, 255, 233, 1) 100%);
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 2vw;
        font-size: 28rpx;
        font-weight: 500;
        color: rgba(22, 24, 30, 1);
      }
    }
  }

  .page2 {
    .main-edit {
      .btns {
        display: flex;

        .btn-item {
          border: 1px solid #fff;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          min-width: 20vw;
          margin-right: 2vw;
          border-radius: 2vw;
          padding: 1vw;

          .icon {
            width: 5vw;
            height: 5vw;
            display: block;
          }
        }
      }
    }
  }
}
</style>